package com.spring.security.handler;

import com.spring.security.entity.User;
import com.spring.security.model.JsonResult;
import com.spring.security.service.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author HouKunLin
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtService jwtService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("text/json");
        response.setCharacterEncoding("UTF-8");
        JsonResult json = JsonResult.ok("登录成功");
        json.data()
                .put("authorities", authentication.getAuthorities())
                .put("credentials", authentication.getCredentials())
                .put("details", authentication.getDetails())
                .put("principal", authentication.getPrincipal())
                .put("authenticated", authentication.isAuthenticated())
                .put("name", authentication.getName())
                .put("class", authentication.getClass().getName())
                .put("token", jwtService.sign((User) authentication.getPrincipal()))
        ;
        response.getWriter().print(json.toJSONString());
    }
}
